<?php

namespace Desktopd\MUA;


// Mailer (MUA)
class Mailer {
    protected $submitter;
    protected $receiver;
    
    
    public function __construct (
        Submitter $submitter = null
        , Receiver $receiver = null
    ) {
        $this->submitter = $submitter;
        $this->receiver = $receiver;
    }
    
    public function getSubmitter () {
        if (!($this->submitter instanceof Submitter)) {
            throw new \RuntimeException("I don't have a Submitter");
        }
        
        return $this->submitter;
    }
    
    public function getReceiver () {
        if (!($this->receiver instanceof Receiver)) {
            throw new \RuntimeException("I don't have a Receiver");
        }
        
        return $this->receiver;
    }
    
    public function createNewMessage () {
        $submitter = $this->getSubmitter();
        
        $senderAddress = $submitter->getSenderAddress();
        if (!($senderAddress instanceof EmailAddress)) {
            throw new \RuntimeException("Could not get a valid sender address!");
        }
        
        $message = new NewMessage($senderAddress);
        return $message;
    }
    
    public function startSubmission () {
        $submitter = $this->getSubmitter();
        
        $submission = $submitter->startSubmission();
        if (!($submission instanceof Submission)) {
            throw new \RuntimeException("Failed to get a valid Submission object");
        }
        
        return $submission;
    }
    
    public function receiveMessages () {
        $receiver = $this->getReceiver();
        
        $messages = $receiver->receiveMessages();
        if (is_array($messages)) {
            $messages = new \ArrayIterator($messages);
        }
        
        if (!($messages instanceof \Traversable)) {
            throw new \RuntimeException("Failed to get a valid Traversable object");
        }
        
        if (!($messages instanceof \Countable)) {
            throw new \RuntimeException("Failed to get a valid Countable object");
        }
        
        return $messages;
    }
}


// vim: ts=4 et ai

